package edu.base.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import edu.base.dao.UsersMapper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.base.model.Users;
import edu.base.service.UsersService;
import edu.base.util.JsonResults;
import edu.base.config.CmsConfig;

@Controller
@RequestMapping("/login")
public class LoginController {

	final static org.slf4j.Logger log = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	UsersService userService;

	@ResponseBody
	@RequestMapping("login")
	public JsonResults login(@RequestParam("login_name") String login_name, String login_pwd, HttpSession session) {
		JsonResults res = new JsonResults();
		Users u = userService.findByLoginName(login_name);
		log.error("登陆" + login_name);
		log.error(u.toString());
		if (u == null) {
			res.setResult_code(false);
			res.setResult_msg("用户名错误");
		} else if (!u.getLoginPwd().equals(login_pwd)) {
			res.setResult_code(false);
			res.setResult_msg("密码错误");
		} else {
			res.setResult_code(true);
			res.setResult_msg("登陆成功");
			HashMap map = new HashMap<String, Object>();
			map.put("user", u);
			res.setResult_arr(map);

			session.setAttribute("user", u);
			session.setAttribute("user_id", u.getUserId());
			session.setAttribute("user_role", u.getRole());
		}

		return res;
	}

	@ResponseBody
	@RequestMapping("loginout")
	public JsonResults loginout(HttpSession session) {
		JsonResults res = new JsonResults();
		session.invalidate();
		return res;
	}

	@RequestMapping("admin_logout")
	public String logout(HttpSession session) {
		session.invalidate();
		log.info("# 用户注销成功 #");
		return "redirect:/login/admin_login";
	}

	/**
	 * 用户登录
	 * 
	 * @return
	 */
	@RequestMapping("admin_login")
	public String admin_login(String error, Model model) throws UnsupportedEncodingException {
		if (error != null) {
			log.info("# 用户登录，错误信息：" + URLDecoder.decode(error, "utf-8"));
			model.addAttribute("error", URLDecoder.decode(error, "utf-8"));
		}
		ModelAndView mv = new ModelAndView();
		return "/login/admin_login";
	}

	/**
	 * BLOG用户登录表单处理
	 * 
	 * @param login_name
	 * @param login_pwd
	 * @param session
	 * @return
	 */
	@RequestMapping("do_admin_login")
	public String do_blog_login(String login_name, String login_pwd, HttpSession session,
			RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {

		log.info("# 用户登录 #" + login_name);
		Users user = userService.findByLoginName(login_name);
		log.info("# 查找到用户 #" + user);
		if (user == null) {
			return "redirect:/login/admin_login";
		} else if (!user.getLoginPwd().equals(login_pwd)) {
			log.debug("# 密码错误 #");
			redirectAttributes.addAttribute("error", URLEncoder.encode("用户名或密码错误", "utf-8"));
			return "redirect:/login/admin_login";
		}else if(user.getState() == 0) {
			log.debug("# 离岗人员无法登陆 #");
			redirectAttributes.addAttribute("error", URLEncoder.encode("离岗人员无法登陆", "utf-8"));
			return "redirect:/login/admin_login";
		}else {
			session.setAttribute("user", user);
			session.setAttribute("user_id", user.getUserId());
			session.setAttribute("user_role", user.getRole());
			log.error("# 登录成功# " + user.toString());
			if (user.getRole() == 0) {
				return "redirect:/admin/index";
			}  else if (user.getRole() == 2) {
				return "redirect:/kefu/index";
			} else if (user.getRole() == 1) {
				return "redirect:/customer/index";
			} else {
				return "redirect:/worker/index";
			}
		}

	}

	@RequestMapping("reg")
	public String reg(String error, Model model) throws UnsupportedEncodingException {
		if (error != null) {
			model.addAttribute("error", URLDecoder.decode(error, "utf-8"));
		}
		return "/login/bbs_reg";
	}

	@RequestMapping("do_reg")
			public String do_reg(String login_name, String login_pwd, String email, String tel, MultipartFile avatar,
					RedirectAttributes redirectAttributes) throws IllegalStateException, IOException {

		if(login_name.isEmpty()){
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("用户名不能为空！", "utf-8"));
			return "redirect:/login/reg";
		}
		if(tel.isEmpty()){
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("手机号不能为空！", "utf-8"));
			return "redirect:/login/reg";
		}
		if(login_pwd.isEmpty()){
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("密碼不能为空！", "utf-8"));
			return "redirect:/login/reg";
		}
		Users u1 = userService.findByLoginName(login_name);
		log.info("用户注册，检查是否已有用户名：" + u1);
		if (u1 != null) {
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("用户名已经存在！", "utf-8"));
			return "redirect:/login/reg";
		}
		if (avatar.isEmpty()) {
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("头像不能为空", "utf-8"));
			return "redirect:/login/reg";
		}
		String savePath = CmsConfig.getUploadPath();
		String fileName = avatar.getOriginalFilename();
		String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String saveName = System.currentTimeMillis() + ext;
		File saveFile = new File(savePath + saveName);
		log.info("save_name:" + saveFile.getAbsolutePath());
		avatar.transferTo(saveFile);
		Users user = new Users();
		user.setLoginName(login_name);
		//user.setLoginPwd(login_pwd);
		user.setLoginPwd(DigestUtils.md5DigestAsHex(login_pwd.getBytes()));
		user.setEmail(email);

		if(userService.findByTel(tel)>0){
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("手机号已存在", "utf-8"));
			return "redirect:/login/reg";
		}
		user.setTel(tel);
		user.setRole(1);
		user.setAvatar("/images/" + saveName);

		userService.insert(user);
		return "redirect:/LoginByName";
	}
	
	
	@RequestMapping("user_edit")
	public String userEdit(Model model, HttpSession session) {
		edu.base.model.Users user = userService.findByKey((Integer) session.getAttribute("user_id"));
		model.addAttribute("user", user);
		return "/customer/user_edit";
	}
	
	@RequestMapping("do_user_edit")
	public String doUserEdit(String login_pwd, MultipartFile avatar,String nick, String email,String tel, HttpSession session) throws IllegalStateException, IOException {
		log.info("用户信息修改 参数：" + login_pwd + avatar);
		Users user = new Users();
		if(!avatar.isEmpty()) {
			String savePath = CmsConfig.getUploadPath();
	    	String fileName = avatar.getOriginalFilename();
	    	String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
	    	String saveName = System.currentTimeMillis() + ext;
	    	File saveFile = new File(savePath + saveName);
	    	log.info("save_name:" + saveFile.getAbsolutePath());
	    	avatar.transferTo(saveFile);
	    	user.setAvatar("/images/" + saveName);
    	}
		user.setNick(nick);
		user.setEmail(email);
		user.setUserId((Integer) session.getAttribute("user_id"));
		user.setTel(tel);

		log.info("用户信息修改：" + user.toString());
		userService.update(user);
		user = userService.findByKey(user.getUserId());
		session.setAttribute("user", user);
		return "redirect:/customer/user_edit";
	}
}
